#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "jerasure.h"
#include "reed_sol.h"

int main( int argc, char** argv )
{
	int *old_bitmatrix;
	char** data_ptrs;
	char** coding_ptrs;
	int i, j;
	FILE* fp;
	unsigned char* buf;
	int m = atoi( argv[1] );
	int k = atoi( argv[2] );
	int w = atoi( argv[3] );
	int erased[k+m];
	old_bitmatrix = reed_sol_vandermonde_coding_matrix( k, m, w );
	srand48(0);
	fp = fopen( argv[4], "r" );

	buf = (unsigned char* ) malloc( sizeof(uint64_t)*(k+m) );
	fread( buf, sizeof(uint64_t), k, fp );
	data_ptrs = (char**) malloc( sizeof( char* ) * k );
	for( i = 0; i < k; i++ )
	{
		data_ptrs[i] = buf + sizeof(uint64_t) * i;
		fwrite( data_ptrs[i], 1, sizeof(uint64_t), stdout );
		fprintf( stdout, "\n" );
		erased[i] = 0;
	}
	coding_ptrs = (char**) malloc( sizeof( char* )  * m );
	for( i = 0; i < m; i++ )
	{
		coding_ptrs[i] = (char*) malloc( sizeof( uint64_t ) );
		erased[i+k] = 0;
	}

	jerasure_matrix_encode( k, m, w, old_bitmatrix, data_ptrs, coding_ptrs, 
			sizeof( uint64_t ) );

	for( i = 0; i < k; i++ )
	{
		fwrite( data_ptrs[i], 1, sizeof(uint64_t), stdout );
		fprintf( stdout, "\n" );
	}
	for( i = 0; i < m; i++ )
	{
		fwrite( coding_ptrs[i], 1, sizeof(uint64_t), stdout );
		fprintf( stdout, "\n" );
	}

	for( i = 0; i < m; i++ )
	{
		j = lrand48() % (k+m);
		if( erased[j] != 0 )
			i--;
		erased[j] = 1;
		if( j < k )
			memset( data_ptrs[j], 0, sizeof(uint64_t) );
		else
			memset( coding_ptrs[j-k], 0, sizeof(uint64_t) );
	}

	for( i = 0; i < k; i++ )
	{
		fwrite( data_ptrs[i], 1, sizeof(uint64_t), stdout );
		fprintf( stdout, "\n" );
	}
	for( i = 0; i < m; i++ )
	{
		fwrite( coding_ptrs[i], 1, sizeof(uint64_t), stdout );
		fprintf( stdout, "\n" );
	}
	jerasure_matrix_decode( k, m, w, old_bitmatrix, 0, erased, data_ptrs, 
			coding_ptrs, sizeof(uint64_t) );
/*
	if( old_bitmatrix != NULL )
		jerasure_print_matrix( old_bitmatrix, m, k, w );
*/
	return 0;
}
